package com.huluobo.document

import com.huluobo.document.entity.DocumentEntity
import com.huluobo.lib_base.BaseRepo
import com.huluobo.lib_base.Res
import com.huluobo.lib_http.Const
import com.huluobo.lib_http.HttpType
import com.huluobo.lib_http.NetworkFactory
import kotlinx.coroutines.flow.Flow
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import javax.inject.Inject

/**
 *  Created by LC on 2025/5/27.
 */
class DocumentRepo @Inject constructor() : BaseRepo() {
    private val apiService by lazy { NetworkFactory.factory(HttpType.NONE).create(ApiService::class.java) }

    fun getDocuments(): Flow<Res<DocumentEntity>> {
        return apiService.getDocuments()
    }


    fun uploadDocument(name: String, path: String, info: String, type: String, resType: String): Flow<Res<Any>> {
        //将文件封装成一个body,注意multipart/form-data 是从接口文档中复制的上传文件类型
        val body = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), File(path))

        //将body转化为一个MultiPartBody,第一个参数是接口文档中的参数名,第二个是文件名,第三个是上面生成的文件body
        val multipartBody = MultipartBody.Builder().addFormDataPart(Const.PARAM_FILE, name, body).build()

        //将multiPartBody中的parts上传
        return apiService.uploadDocument(multipartBody.parts, info, type, resType)
    }

    fun deleteDocument(id: Int): Flow<Res<Any>> {
        return apiService.deleteDocument(id)
    }
}